package com.ccx.coachsite.ui.login;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.Properties;
import java.util.UUID;

import org.apache.http.client.utils.URIUtils;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.Intent;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.provider.Settings.Secure;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.ccx.coachsite.bus.SharedKey;
import com.ccx.coachsite.task.LoginStaticTask;
import com.ccx.coachsite.util.SharedPreferencesUtil;
import com.ccx.coachsite.util.StringUtil;

public final class LoginHelper {

	/**
	 * 获取应用版本名称
	 * 
	 * @param context
	 * @return
	 */
	public static String getVersionName(Context context) {
		String versionName = "";
		try {
			versionName = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 1).versionName;
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
		}
		return versionName;
	}

	/**
	 * 获取应用版本号
	 * 
	 * @param context
	 * @return
	 */
	public static int getVersionCode(Context context) {
		int versionCode = 0;
		try {
			versionCode = context.getPackageManager().getPackageInfo(
					context.getPackageName(), 1).versionCode;
		} catch (NameNotFoundException e) {
			// e.printStackTrace();
		}
		return versionCode;
	}

	public static boolean requireLogin(final Context context) {
		String mobile = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_UserId_Key, "");
		if (TextUtils.isEmpty(mobile)) {
			Log.d("CoashSite.requireLogin", "-------never login------");
			new AlertDialog.Builder(context).setTitle("您还未登录，是否登录？")
					.setPositiveButton("是", new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							Intent intent = new Intent(context,
									LoginActivity.class);
							context.startActivity(intent);
						}
					}).setNegativeButton("否", null).create().show();
			return false;
		}
		return true;
	}

	public static boolean isLogin(Context context) {

		String mobile = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_UserId_Key, "");
		return !TextUtils.isEmpty(mobile);
	}

	public static boolean isFirstLogin(Context context) {
		String userId = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_UserId_Key, "");
		if (StringUtil.isEmpty(userId))
			return false;

		String loginUserId = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_Login_UserId_Key, "");
		if (StringUtil.isEmpty(loginUserId))
			return true;

		String userIdKey = "." + userId + ".";
		return loginUserId.indexOf(userIdKey) < 0;
	}

	public static void setCurrentLogined(Context context) {
		String userId = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_UserId_Key, "");
		if (StringUtil.isEmpty(userId))
			return;

		String loginUserId = SharedPreferencesUtil.getValue(context,
				SharedKey.Shared_Login_UserId_Key, "");
		if (StringUtil.isEmpty(loginUserId))
			loginUserId = "";

		String userIdKey = "." + userId + ".";
		loginUserId += "_" + userIdKey;
		SharedPreferencesUtil.setValue(context,
				SharedKey.Shared_Login_UserId_Key, loginUserId);

	}

	/**
	 * 获取IMSI
	 * 
	 * @param context
	 * @return
	 */
	public static String getMobileIMSI(Context context) {
		String result = "";
		try
		{
			TelephonyManager telMgr = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			if (telMgr != null)
				result = telMgr.getSubscriberId();
		}
		catch(Exception e)
		{
			
		}
		return result;
		
	}
	
	/**
	 * 获取IMEI
	 * 
	 * @param context
	 * @return
	 */
	public static String getMobileIMEI(Context context) {
		String result = "";
		try
		{
			TelephonyManager telMgr = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
			if (telMgr != null)
				result = telMgr.getDeviceId();
			String strid = android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);
			if(!StringUtil.isEmpty(strid))
				result += "_"+strid;
		}
		catch(Exception e)
		{
			
		}
		return result;
	}
	
	public static String DeviceUuidFactory(Context context) {
	  String PREFS_FILE = "device_id.xml";
	  String PREFS_DEVICE_ID = "device_id";
	  UUID uuid = null;
        if( uuid ==null ) {
                if( uuid == null) {
                    final SharedPreferences prefs = context.getSharedPreferences( PREFS_FILE, 0);
                    final String id = prefs.getString(PREFS_DEVICE_ID, null );
                    if (id != null) {
                        // Use the ids previously computed and stored in the prefs file
                        uuid = UUID.fromString(id);
                    } else {
                        final String androidId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);
                        // Use the Android ID unless it's broken, in which case fallback on deviceId,
                        // unless it's not available, then fallback on a random number which we store
                        // to a prefs file
                        try {
                            if (!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8"));
                            } else {
                                final String deviceId = ((TelephonyManager) context.getSystemService( Context.TELEPHONY_SERVICE )).getDeviceId();
                                uuid = deviceId!=null ? UUID.nameUUIDFromBytes(deviceId.getBytes("utf8")) : UUID.randomUUID();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }
                        // Write the value out to the prefs file
                        prefs.edit().putString(PREFS_DEVICE_ID, uuid.toString() ).commit();
                    }
                }
        }
            
        if(uuid != null)
           return uuid.toString();
             
        return "";
    }
    
	public static String getLocalMacAddress(Context context) {    
		String result = "";
		try
		{
			
			
			WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
			WifiInfo info = wifi.getConnectionInfo();         
			result = info.getMacAddress();     
			
			try {  
	            for (Enumeration<NetworkInterface> en = NetworkInterface  
	                    .getNetworkInterfaces(); en.hasMoreElements();) {  
	                NetworkInterface intf = en.nextElement();  
	                result = info.getMacAddress();     
	                for (Enumeration<InetAddress> enumIpAddr = intf  
	                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {  
	                    InetAddress inetAddress = enumIpAddr.nextElement();  
	                    
	                    if (!inetAddress.isLoopbackAddress()) {  
	                    	result = inetAddress.getHostAddress().toString();  
	                    }  
	                }  
	            }  
	        } catch (Exception ex) {  
	            Log.e("WifiPreference IpAddress", ex.toString());  
	        }  
		}
		catch(Exception e)
		{
			
		}
		return result;
		
	} 

	public static boolean isExpert(Context context) {
		return SharedPreferencesUtil.getBoolean(context,
				SharedKey.Shared_Is_Expert);
	}

	public static void doLoginStatic(Context context, String mobile,
			String userId) {
		LoginStaticTask lst = new LoginStaticTask(null, context);
		lst.imei = LoginHelper.getMobileIMEI(context);
		lst.imsi = LoginHelper.getMobileIMSI(context);
		lst.version = LoginHelper.getVersionName(context);
		lst.mobile = mobile;
		lst.userId = userId;
		lst.execute();
	}
}
